import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_yyt/models/care_report_entity.dart';
import 'package:ls_work/a_yyt/models/service_area_entity.dart';
import 'package:ls_work/a_yyt/widget/care_report_cell.dart';
import 'package:ls_work/mvp/base_page_state.dart';
import 'package:ls_work/a_yyt/presenter/care_search_presenter.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/provider/base_list_provider.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/my_refresh_list.dart';
import 'package:ls_work/widgets/search_bar.dart' as e;
import 'package:ls_work/widgets/state_layout.dart';
import 'package:provider/provider.dart';

class CareSearchPage extends StatefulWidget {
  // final int fromType;
  // CareSearchPage({Key key, this.fromType = 0});
  @override
  CareSearchPageState createState() => CareSearchPageState();
}

class CareSearchPageState
    extends BasePageState<CareSearchPage, CareSearchPresenter>
    with SingleTickerProviderStateMixin {
  BaseListProvider<CareInfo> provider = BaseListProvider<CareInfo>();
  List<ServiceAreaInfo> areaList = [];
  String _keyword = '';
  int _page = 1;
  String _starTime = '';
  String _endTime = '';
  DateTime? _startDateTime;
  DateTime? _endDateTime;
  String _serviceAreaIds = '';

  Animation<double>? animation;
  AnimationController? controller;

  @override
  initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectServiceAreaData();
    });
    provider.setStateTypeNotNotify(StateType.empty);
    controller = new AnimationController(
        duration: const Duration(milliseconds: 500), vsync: this);
    //图片宽高从0变到300
    animation = new Tween(begin: 0.0, end: 300.0).animate(controller!);
  }

  dispose() {
    //路由销毁时需要释放动画资源
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<BaseListProvider<CareInfo>>(
      create: (_) => provider,
      child: Scaffold(
        appBar:e.SearchBar(
          hintText: "请输入长者姓名查询",
          isShowRightbutton: true,
          onRightButtonClick: (isHidden) {
            isHidden ? controller?.reverse() : controller?.forward();
          },
          onPressed: (text) {
            controller?.reverse();
            FocusScope.of(context).unfocus();
            _keyword = text;
            provider.setStateType(StateType.loading);
            _onRefresh();
          },
        ),
        body: Consumer<BaseListProvider<CareInfo>>(
          builder: (_, provider, __) {
            return Stack(
              fit: StackFit.expand,
              children: [
                DeerListView(
                  key: Key('order_search_list'),
                  itemCount: provider.list.length,
                  stateType: provider.stateType,
                  onRefresh: _onRefresh,
                  loadMore: _loadMore,
                  hasMore: provider.hasMore,
                  itemBuilder: (_, index) {
                    return CareReportCell(
                      info: provider.list[index].bean!,
                    );
                  },
                ),
                Positioned(
                  left: 0,
                  right: 0,
                  top: 0,
                  child: AnimatedBuilder(
                    animation: animation!,
                    child: _topFiltterView(),
                    builder: (context, child) {
                      return Container(
                        height: animation?.value,
                        width: ScreenUtil.getScreenW(context),
                        child: child,
                      );
                    },
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _topFiltterView() {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.fromLTRB(15, 15, 15, 30),
        color: Colours.bg_color,
        width: ScreenUtil.getScreenW(context),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  '发生时间',
                  style: TextStyles.textDark18,
                ),
                Gaps.hGap15,
                Container(
                  width: 200,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: InkWell(
                    onTap: () {
                      _showTimePicker(type: 0);
                    },
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            _starTime,
                            textAlign: TextAlign.center,
                            style: TextStyles.textNormal18,
                          ),
                        ),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colours.text_gray,
                        )
                      ],
                    ),
                  ),
                ),
                Gaps.hGap15,
                Text(
                  '至',
                  style: TextStyles.textDark18,
                ),
                Gaps.hGap15,
                Container(
                  width: 200,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: InkWell(
                    onTap: () {
                      _showTimePicker(type: 1);
                    },
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            _endTime,
                            textAlign: TextAlign.center,
                            style: TextStyles.textNormal18,
                          ),
                        ),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colours.text_gray,
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.only(top: 15, bottom: 8),
              child: Text(
                '区域',
                style: TextStyles.textDark20,
              ),
            ),
            Wrap(
              spacing: 15,
              children: List<Widget>.generate(
                areaList.length,
                (int index) {
                  return ChoiceChip(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    label: Text('${areaList[index].name ?? ''}'),
                    backgroundColor: Colours.text_gray,
                    selectedColor: Colors.blue[300],
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(3.0),
                    ),
                    onSelected: (bool selected) {
                      setState(() {
                        areaList[index].isSelected = selected;
                      });
                    },
                    selected: areaList[index].isSelected,
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    var tempList = [];
    for (var item in areaList) {
      if (item.isSelected) {
        tempList.add(item.id);
      }
    }
    if (tempList.length > 0) {
      _serviceAreaIds = tempList.join(',');
    }
    await presenter.fectData(
      true,
      page: _page,
      elderNameLike: _keyword,
      createDateEnd: _endTime,
      createDateStart: _starTime,
      serviceAreaIds: _serviceAreaIds,
    );
  }

  Future _loadMore() async {
    _page++;
    await presenter.fectData(
      true,
      page: _page,
      elderNameLike: _keyword,
      createDateEnd: _endTime,
      createDateStart: _starTime,
      serviceAreaIds: _serviceAreaIds,
    );
  }

  @override
  CareSearchPresenter createPresenter() {
    return CareSearchPresenter();
  }

  _fectServiceAreaData() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post('${HttpApi.serviceAreaList}').then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            ServiceAreaEntity model = ServiceAreaEntity.fromJson(map['data']);
            setState(() {
              areaList = model.rows??[];
            });
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///调起时间选择器
  _showTimePicker({int? type}) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1900-01-01 00:00"),
      maxDateTime: DateTime.now(),
      initialDateTime: DateTime.now(),
      dateFormat: DateFormats.y_mo_d,
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.date, // show TimePicker
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          print(dateTime);
          if (dateTime == null) {
            return;
          }
          if (type == 0) {
            _startDateTime = dateTime;
            _starTime =
                DateUtil.formatDate(dateTime, format: DateFormats.y_mo_d);
          } else {
            _endDateTime = dateTime;
            _endTime =
                DateUtil.formatDate(dateTime, format: DateFormats.y_mo_d);
          }
          if (_startDateTime != null && _endDateTime != null) {
            if (_endDateTime!.compareTo(_startDateTime!) == -1) {
              Toast.show('结束时间必须大于开始时间');
              setState(() {
                _endDateTime = null;
                _endTime = '';
              });
            }
          }
        });
      },
    );
  }
}
